package com.huangmb.anymark.server.dao.impl;

import com.huangmb.anymark.server.dao.BaseDao;
import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * @author hmb
 * @version 1.0
 * @since 2016/5/4 20:36
 */
public class BaseDaoImpl<T> implements BaseDao<T> {

    @Resource(name = "sessionFactory")
    private SessionFactory mSessionFactory;
    private Class<T> mClass;

    @SuppressWarnings("unchecked")
    public BaseDaoImpl() {
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        mClass = (Class<T>) type.getActualTypeArguments()[0];
        System.out.println("DAO实例:" + mClass.getSimpleName());
    }

    public Session getSession() {
        return mSessionFactory.getCurrentSession();
    }

    @Override
    public void save(T entity) {
        getSession().save(entity);
    }

    @Override
    public void update(T entity) {
        getSession().update(entity);
    }

    @Override
    public void delete(Serializable id) {
        getSession().delete(this.findById(id));
    }

    @Override
    @SuppressWarnings("unchecked")
    public T findById(Serializable id) {
        return (T) getSession().get(mClass, id);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<T> findByHQL(String hql, Object... params) {
        Query query = getSession().createQuery(hql);
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                query.setParameter(i,params[i]);
            }
        }
        return query.list();
    }
}
